package table;

import intermediate_representation.*;
import symbal.Symbal;
import symbal.SymbalTable;

import java.util.ArrayList;

public class InterCodeTable {
    public static int regindex = 0;
    public static String nowVar = "";
    public static ArrayList<InterRP> interCode = new ArrayList<>();
    public static SymbalTable symbalTable = new SymbalTable();
    public static SymbalTable constTable = new SymbalTable();
    public static SymbalTable globalTable = new SymbalTable();
    public static ArrayList<Symbal> paraTable = new ArrayList<>();
    public static boolean global = true;
    public static int varnum = 0;
    public static int constnum = 0;
    public static int paranum = 0;
    public static int funcnum = 0;
    public static int labelnum = 0;
    public static String nowWhileBeginLabel = null;
    public static String nowWhileEndLabel = null;



    public static SymbalTable getSymbalTable() {
        return symbalTable;
    }

    public static void pushvar() {
        setvar();
        regindex++;
    }

    public static void setvar() {
        nowVar = "$reg" + regindex;
    }

    public static void addCode(InterRP interRP) {
        interCode.add(interRP);
    }

    public static void setLastName(String name) {
        InterRP lastrp = interCode.get(interCode.size() - 1);
        if (lastrp instanceof AssignRP) {
            ((AssignRP) lastrp).setResult(name);
        } else if (lastrp instanceof ExpRP) {
            ((ExpRP) lastrp).setResult(name);
        } else if (lastrp instanceof CallRP) {
            ((CallRP) lastrp).setResult(name);
        }
    }

    public static void endGlobal() {
        global = false;
        globalTable.clear();
    }

    public static String pushLabel() {
        String newLabel = "Label_" + InterCodeTable.labelnum;
        InterCodeTable.labelnum++;
        return newLabel;
    }

    public static boolean isConst(String str, SymbalTable table1, SymbalTable table2) {
        boolean cs = table1.checkDupSymbal(str);
        boolean cc = table2.checkDupSymbal(str);
        if (cs && cc) {
            return true;
        } else if (cs && !cc) {
            return false;
        } else {
            return isConst(str, table1.getFather(), table2.getFather());
        }
    }

    public static boolean isConst(String str) {
        return isConst(str, symbalTable, constTable);
    }
}
